import { title } from 'process';
import { type RouteRecordRaw } from 'vue-router';
// import {  RouteRecordRaw } from 'vue-router';
import router from '/@/router';
import { uniqueSlash, isUrl } from '/@/utils/is';
// const modules = import.meta.globEager('@/views/*/*.vue')
// const components = import.meta.globEager('./views/**/*.vue');
const modules = import.meta.glob('../views/**/*.vue')
import RouterViews from '/@/layout/index.vue';
// import { type PermissionType } from '@/core/permission/modules/types';
// import router from '/@/router';
// 需要放在所有路由之后的路由
// const endRoutes: RouteRecordRaw[] = [REDIRECT_ROUTE, errorRoute, notFound];
export const routes: Array<RouteRecordRaw> = [
  // {
  //   path: '/',
  //   name: 'Layout',
  //   redirect: '/dashboard/welcome',
  //   component: () => import(/* webpackChunkName: "layout" */ '@/layout/index.vue'),
  //   meta: {
  //     title: '首页',
  //   },
  //   children: [],
  // },
  // Layout之外的路由
  // ...outsideLayout,
];
const constantRouterComponents = {};



export function filterAsyncRoute(
  routes: API.Menu[],
  parentRoute: API.Menu | null = null,
  lastNamePath: string[] = [],
) {

  return routes
    .filter((item) => item.type !== 2 && item.isShow && item.parentId == parentRoute?.id)
    .map((item) => {
      const { router, viewPath, name, icon, orderNum, keepalive } = item;
      let fullPath = '';
      const pathPrefix = lastNamePath.slice(-1)[0] || '';
      if (isUrl(router)) {
        fullPath = router;
      } else {
        fullPath = router.startsWith('/') ? router : `/${router}`;
        fullPath = router.startsWith(pathPrefix) ? fullPath : pathPrefix + fullPath;
        fullPath = [...new Set(uniqueSlash(fullPath).split('/'))].join('/');
      }
      let realRoutePath = router;
      if (parentRoute) {
        if (fullPath.startsWith(parentRoute?.router)) {
          realRoutePath = fullPath.split(parentRoute.router)[1];
        } else if (!isUrl(parentRoute.router) && !isUrl(router)) {
          realRoutePath = router;
        }
      }
      realRoutePath = realRoutePath.startsWith('/') ? realRoutePath.slice(1) : realRoutePath;
      const route: any = {
        path: realRoutePath,
        // fullPath
        // name: `${viewPath ? toHump(viewPath) : fullPath}-${item.id}`,
        name: name,

        meta: {

          rank: orderNum,

          title: name,

          icon: "lollipop",

        },
      };

      if (item.type === 0) {
        // 如果是目录
        const children = filterAsyncRoute(routes, item, lastNamePath.concat(fullPath));
        if (children?.length) {
          // route.component = RouterViews;
          const Layout = () => import("/@/layout/index.vue");
          const ParentView = () => import("/@/components/ParentView/index.vue");
          // if (item.parentId) {
          //解决多级目录
          route.component = ParentView
          // } else {
          //   route.component = Layout
          // }
          route.path = "/" + route.path;
          route.children = children;
          // console.log(children[0], "children[0]");
          // route.redirect = '/sys/permssion/user'
        } else {

        }
        return route;
      } else if (item.type === 1) {
        // 如果是页面

        // viewPath
        // console.log(item.viewPath)
        // const viewPath = item.viewPath
        // route.component = () => import(`/@/+${item.viewPath}`)

        // route.component = () => import(`/@/views/system/permission/user/index.vue`)
        route.component = modules[`../${item.viewPath}/index.vue`]
        // route.component = () => require(`/@/${item.viewPath}/index.vue`),

        // route.component = () => import(`/@/${item.viewPath}/index.vue`)
        route.path = item.router
        const perms = routes
          .filter((n) => n.parentId === item.id)
          .flatMap((n) => n.perms?.split(','));
        if (route.meta && perms) {
          // 设置当前页面所拥有的权限

          // redirect: "/permission/page/index",
          //   rank: 7,
          route.meta.icon = "lollipop"
          route.meta.rank = item.orderNum,
            route.meta.perms = perms as PermissionState[];
        }
        return route;
      }


    })
    .filter((item): item is RouteRecordRaw => !!item);
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (asyncMenus: API.Menu[]) => {
  try {
    console.log("test", asyncMenus)
    const routeList = filterAsyncRoute(asyncMenus);

    return routeList
  } catch (error) {
    console.error('生成路由时出错', error);
    return {
      menus: [],
      routes: [],
    };
  }
}